package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * * @title: QuanZiService
 *
 * @Author Philcan
 * @Date: 2021/8/11 19:34
 * @Version 1.0
 */
@Service
public class QuanZiService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PicUploadService picUploadService;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;
    @Autowired
    private QuanziMQService quanziMQService;

    public PageResult queryPublishList(Integer page, Integer pageSize, String token) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPageSize(pageSize);

        User user = this.userService.queryUserByToken(token);
        if (user == null) {
            return pageResult;
        }

        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        getRecords(records, quanZiVoList);

        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }


    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ","));

        User user = UserThreadLocal.get();
        quanZiVo.setCommentCount(0);
        quanZiVo.setDistance("1.2公里");
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0);
        quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId())));
        quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0);
        quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId())));
    }

    public String savePublish(String textContent, String location, String latitude, MultipartFile[] multipartFile) {
        User user = UserThreadLocal.get();
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(latitude);
        publish.setSeeType(1);
        List<String> picUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult upload = this.picUploadService.upload(file);
            picUrls.add(upload.getName());
        }
        publish.setMedias(picUrls);

        String savePublish = this.quanZiApi.savePublish(publish);
        if (StrUtil.isNotEmpty(savePublish)) {
            this.quanziMQService.publishMsg(savePublish);
        }
        return savePublish;

    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPageSize(pageSize);

        User user = UserThreadLocal.get();

        PageInfo<Publish> pageInfo = this.quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        pageResult.setItems(this.fillQuanziVo(records));
        return pageResult;
    }

    private List<QuanZiVo> fillQuanziVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        getRecords(records, quanZiVoList);
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }
        return quanZiVoList;
    }

    private void getRecords(List<Publish> records, List<QuanZiVo> quanZiVoList) {
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVoList.add(quanZiVo);
        });
    }

    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.likeComment(user.getId(), publishId);
        if (result) {
            this.quanziMQService.likePublishMsg(publishId);
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if (result) {
            this.quanziMQService.disLikePublishMsg(publishId);
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.loveComment(user.getId(), publishId);
        if (result) {
            this.quanziMQService.lovePublishMsg(publishId);
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    public Long disLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.disLoveComment(user.getId(), publishId);
        if (result) {
            this.quanziMQService.disLovePublishMsg(publishId);
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish != null) {
            return null;
        }
        this.quanziMQService.queryPublishMsg(publishId);
        return this.fillQuanziVo(Arrays.asList(publish)).get(0);
    }

    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPageSize(pageSize);

        User user = UserThreadLocal.get();

        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        List<CommentVo> result = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(Integer.valueOf(DateUtil.format(new Date(record.getCreated()), "HH:mm")));
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(record.getUserId(), userInfo.getUserId())) {
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            result.add(commentVo);
        }
        pageResult.setItems(result);
        return pageResult;
    }

    public Boolean saveComments(String publishId, String comment) {
        User user = UserThreadLocal.get();
        Boolean bool = this.quanZiApi.saveComment(user.getId(), publishId, comment);
        if (bool) {
            this.quanziMQService.commentPublishMsg(publishId);
        }
        return bool;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPageSize(pageSize);

        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        if (CollUtil.isEmpty(pageInfo.getRecords())) {
            return pageResult;
        }
        pageResult.setItems(this.fillQuanziVo(pageInfo.getRecords()));
        return pageResult;
    }

    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        VisitorsVo visitorsVo = null;
        for (Visitors visitors : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitors.getVisitorUserId(), userInfo.getUserId())) {
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StrUtil.split(userInfo.getTags(), ","));
                    visitorsVo.setFateValue(visitors.getScore().intValue());
                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }
}
